# -*- coding:utf8 -*-
from numpy import *
import string

def loadTrainData(path):
    trainData = {}
    fid = open(path)
    lines = fid.readlines()
    for line in lines:
        data = line.split('\t',7)
        feature = map(string.atoi,data[3:6])
        if data[0] not in trainData:
            trainData[data[0]] = [feature]
        else:
            trainData[data[0]].append(feature)
    fid.close()
    return trainData
def splitData(data):
    trainData = {}
    testData = {}
    for user in data:
        feature = data[user]
        num = len(feature)
        trainFeat = feature[0:(num/4)*3]
        testFeat = feature[(num/4)*3:]
        trainData[user] = trainFeat
        testData[user] = testFeat
    return trainData,testData         
def computeMean(trainData):
    mean = {}
    i = 1
    for user in trainData:
        feature = array(trainData[user])
        if len(feature) == 0:
            continue
        mean[user] = feature.sum(0)/feature.shape[0]
        i = i +1
    return mean
def test(testData,mean):
    result = {}
    for user in testData:
        data = testData[user]
        r = [];
        for i in range(len(data)):
            if user not in mean:
                predict = [0,0,0]
            else:
                predict = list(mean[user])
            r.append(predict)
        result[user] = r 
    return result
def computeAcc(testData,result):
    up = 0;
    down = 0;
    for user in result:
        pre = result[user]
        re = testData[user]
        for i in range(len(re)):
            p = pre[i]
            r = re[i]
            Ef = abs(p[0] - r[0])/float(r[0] + 5)
            Ec = abs(p[1] - r[1])/float(r[1] + 3)
            El = abs(p[2] - r[2])/float(r[2] + 3)
            ci = r[0] + r[1] +r[2]
            if ci > 100:
                ci = 100
            pi = 1 - 0.5 * Ef - 0.25 * Ec - 0.25 * El
            if pi > 0.8:
                pi = 1
            else:
                pi = 0
            up = up + (ci + 1)*pi
            down = down +  (ci + 1)
    acc = up/float(down)
    return acc        
if __name__ == "__main__":
    print "load data..."
    trainPath = "/home/lab-xu.zeke/ZakeXu/WeiboPred/dataSet/weibo_train_data.txt"
    data = loadTrainData(trainPath)
    print "split data..." 
    [trainData,testData] = splitData(data)
    print "compute mean..."
    mean = computeMean(trainData)
    print "test..."
    result = test(testData, mean)
    print "compute acc..."
    acc = computeAcc(testData, result)
    #print "trainData:\n",trainData
    #print "testData:\n",testData
    #print "result:\n",result
    print "acc:\n",acc
    print "finish"
 